import asyncio
from playwright.async_api import async_playwright
import os
from dao.BaseRepository import BaseRepository
from loguru import logger
import pymongo
import re
import time
baseRep = BaseRepository(collectionname="switch")
async def main():
    async with async_playwright() as p:        
        browser = await p.chromium.launch(headless=False,slow_mo=100)
        if os.path.exists("state.json"):
            context = await browser.new_context(storage_state="state.json")
        else:
            context = await browser.new_context()
        # create a new page inside context.
        page = await context.new_page()
        await page.goto("https://pan.baidu.com/disk/main?from=homeFlow#/index?category=all")
        # dispose context once it is no longer needed.
        results, nums, _ = baseRep.get_all_no_page(sort=["_id",pymongo.DESCENDING])
        # print(nums)
        # print(results[:10])
        
        for r in results:
            try:
                print(r.get("name"))
                print(r.get("_id"))
                status = r.get("status", "need_save")
                logger.info(f"status:{status}")
                if status!="need_save":
                    continue
                if "pwd=" not in r.get("pan_link") and r.get("pan_code") is not None:
                    link=str(r.get("pan_link")).strip().split("?")[0]+"?pwd="+ str(r.get("pan_code")).strip()
                else:
                    link=str(r.get("pan_link")).strip()
            
                await page.goto(link)
                if "不存在" in await page.title():
                    continue
                await page.get_by_role("list").locator("div span").first.click()
                time.sleep(1)
                await page.get_by_role("link", name="保存到网盘").click()                                
                
                time.sleep(1)
                if await page.get_by_text("最近保存路径：/games04024").is_visible():

                    await page.get_by_text("最近保存路径：/games04024").click()
                else:
                    await page.get_by_text("games04024").click()
                await page.get_by_role("link", name="确定").click()
                time.sleep(1)
                await page.get_by_text("保存成功").is_enabled()
                time.sleep(1)
                await page.locator(".fx-icon-close").click()            
                time.sleep(3)
                r["status"] = "saved"
                baseRep.update_by_id(r.get("_id"), r)
            except Exception as e:
                logger.error(str(e))
                r["status"] = "need_save"
                baseRep.update_by_id(r.get("_id"), r)
                time.sleep(3)
                continue
        storage = await context.storage_state(path="state.json")
        
        await context.close()
       
 


asyncio.run(main())
